'use strict';

/**
 * @ngdoc service
 * @name jgappApp.RongYService
 * @description
 * # RongYService
 * Service in the jgappApp.
 */
angular.module('jgappApp')
    .service('RongYService', function (DataService, openApi, $location, $window, $q, Groups, RongYapi, $rootScope, newMessageEventService, Util, ChatStatus) {
        var RongYService = {};
        var login = function (params) {
            var token;
            var defer = $q.defer();
            RongYapi.getToken().then(function (ret, err) {
                if (ret) {
                    console.log("login data:" + JSON.stringify(ret));
                    if (ret) {
                        token = ret.data.result;
                        defer.resolve(token);
                    }
                }
                if (err) {
                    console.log("login err:" + JSON.stringify(err));
                }
            });
            return defer.promise;
        }

        var initRong = function (token) {
            $rootScope.arrMsgs = [];
            $rootScope.arrCons = [];
            RongCloudLibPlugin.init({
                appKey: "pvxdm17jx4jhr",
            },
                function (ret, err) {
                    if (ret) {
                        console.log('init:' + JSON.stringify(ret));
                    }
                    if (err) {
                        console.log('init error:' + JSON.stringify(err));
                    }
                }

            );
            RongCloudLibPlugin.connect({
                token: token
            },
                function (ret, err) {
                    if (ret) {
                        console.log('connect:' + JSON.stringify(ret));
                        $rootScope.curUID = ret.result.userId;
                        $rootScope.$apply();
                    }
                    if (err) {
                        console.log('init error:' + JSON.stringify(err));
                    }
                }
            );
            RongCloudLibPlugin.setConnectionStatusListener(
                function (ret, err) {
                    if (ret) {
                        console.log('setConnectionStatusListener:' + JSON.stringify(ret));
                        if (ret.result.connectionStatus == 'KICKED') {
                            Util.logoutUser();//注销当前用户
                            Util.Toast("您的帐号已在其他端登录,请重新登录", {
                                callback: function () {
                                    $location.path("login/login");
                                }
                            })
                        }
                    }
                    if (err) {
                        console.log('setConnectionStatusListener error:' + JSON.stringify(err));
                    }
                }
            );
            RongCloudLibPlugin.setOnReceiveMessageListener(
                function (ret, err) {
                    if (ret) {
                        console.log('setOnReceiveMessageListener:' + JSON.stringify(ret));
                        $rootScope.arrMsgs.push(JSON.stringify(ret.result.message));
                        // 设置全局角标，表示有信息
                        $rootScope.haveMsgs = true
                        $rootScope.$apply();
                    }
                    if (err) {
                        console.log('setOnReceiveMessageListener error:' + JSON.stringify(err));
                    }
                }

            );

        }
        RongYService.init = function () {
            login().then(function (token) {
                // 登陆成功后初始化监听事件，获取用户好友列表
                initRong(token);
                // 监听数据变化
                var chMsg = function (newValue, oldValue) {
                    if (newValue !== oldValue) {
                        var jsonMsg = newValue.pop();
                        if (typeof jsonMsg !== "undefined" && jsonMsg !== "undefined") {
                            console.log('begin broadcast');
                            // $rootScope.$broadcast('newMessage', jsonMsg);
                            newMessageEventService.broadcast(jsonMsg);
                        }
                    }
                };
                var listener = $rootScope.$watch('arrMsgs', chMsg, true); //只用watch着items的变化

            })
        };
        RongYService.goPravite = function (userId) {
            $location.path("/chat/chatroom/" + userId + "/PRIVATE").replace()
        };
        RongYService.goGroup = function (groupId) {
            $location.path("/chat/chatroom/" + groupId + "/GROUP").replace()
        };
        // 获取所有未读消息数
        RongYService.getTotalUnreadCount = function (targetId, conversationType) {
            var defer = $q.defer();
            RongCloudLibPlugin.getTotalUnreadCount(function (ret, err) {
                if (ret) {
                    defer.resolve(ret.result);
                } else if (err) {
                    console.log("getTotalUnreadCount error: " + JSON.stringify(err));
                }
            })

            return defer.promise;
        };
        // 标记已读
        RongYService.clearMessagesUnreadStatus = function (targetId, conversationType) {
            var defer = $q.defer();
            RongCloudLibPlugin.clearMessagesUnreadStatus({
                conversationType: conversationType,
                targetId: targetId
            },
                function (ret, err) {
                    if (ret && ret.result) {
                        defer.resolve(ret.result.discussionId);
                    } else if (err) {
                        console.log("clearMessagesUnreadStatus error: " + JSON.stringify(err));
                    }
                }
            );
            return defer.promise;
        };
        // 获取所有会话
        RongYService.getConversationList = function () {
            var defer = $q.defer();
            RongCloudLibPlugin.getConversationList(
                function (ret, err) {
                    if (ret) {
                        defer.resolve(ret);
                    }
                    if (err) {
                        console.log('getConversationList err:' + JSON.stringify(err));
                    }

                }
            );
            return defer.promise;
        };
        // 移除所有会话
        RongYService.clearConversations = function () {
            var defer = $q.defer();
            RongCloudLibPlugin.clearConversations({
                conversationTypes: ["PRIVATE", "DISCUSSION", "GROUP"]
            },
                function (ret, err) {
                    if (ret) {
                        defer.resolve(ret)
                    }
                    if (err) {
                        console.log('clearConversition err:' + JSON.stringify(err));
                    }
                }

            );
            return defer.promise;
        };
        // 移除某个会话
        RongYService.removeConversation = function (curconversiton) {
            var defer = $q.defer();
            RongCloudLibPlugin.removeConversation({
                conversationType: curconversiton.conversationType,
                targetId: curconversiton.targetId
            }, function (ret, err) {
                if (ret && ret.status == 'success') {
                    defer.resolve();
                }
            })

            return defer.promise;
        };
        // 获取消息提醒状态
        RongYService.getConversationNotificationStatus = function (targetId, conversationType) {
            var defer = $q.defer();
            RongCloudLibPlugin.getConversationNotificationStatus({
                conversationType: conversationType,
                targetId: targetId
            }, function (ret, err) {
                if (ret && ret.status == 'success') {
                    defer.resolve(ret.result);
                } else {
                    console.log(err.result.code);
                }
            })
            return defer.promise;
        };
        // 设置消息提醒状态
        RongYService.setConversationNotificationStatus = function (targetId, conversationType, notificationStatus) {
            var defer = $q.defer();
            RongCloudLibPlugin.setConversationNotificationStatus({
                conversationType: conversationType,
                targetId: targetId,
                notificationStatus: notificationStatus
            }, function (ret, err) {
                if (ret && ret.status == 'success') {
                    defer.resolve(ret.result);
                } else {
                    console.log(err.result.code);
                }
            })
            return defer.promise;
        };
        // 创建群组
        RongYService.creategroup = function (param) {
            var defer = $q.defer();
            DataService.getData(openApi.creategroup, param).then(function (data) {
                defer.resolve(data);
            })
            return defer.promise;
        };
        // 更新群组
        RongYService.updateGroup = function (param) {
            var defer = $q.defer();
            DataService.getData(openApi.joingroup, param).then(function (data) {
                defer.resolve(data);
            })
            return defer.promise;
        };
        // 更新群组名称
        RongYService.refreshgroup = function (param) {
            var defer = $q.defer();
            DataService.getData(openApi.refreshgroup, param).then(function (data) {
                defer.resolve(data);
            })
            return defer.promise;
        };
        // 获取群组详情
        RongYService.getGroup = function (param) {
            var defer = $q.defer();
            DataService.getData(openApi.getGroup, param).then(function (data) {
                defer.resolve(data);
            })
            return defer.promise;
        };
        // 移出或者退出群
        RongYService.quitGroup = function (param) {
            var defer = $q.defer();
            DataService.getData(openApi.quitgroup, param).then(function (data) {
                defer.resolve(data);
            })
            return defer.promise;
        };
        // 解散群
        RongYService.dismissgroup = function (param) {
            var defer = $q.defer();
            DataService.getData(openApi.dismissgroup, param).then(function (data) {
                defer.resolve(data);
            })
            return defer.promise;
        };
        // 设置免打扰时间
        RongYService.setNotificationQuietHours = function (param) {
            var defer = $q.defer();
            RongCloudLibPlugin.setNotificationQuietHours({
                startTime: '00:00:00',
                spanMinutes: 1430 //设置间隔时间
            }, function (ret, err) {
                if (ret) {
                    defer.resolve(ret.status);
                }
            })
            return defer.promise;
        };
        // 清除免打扰设置
        RongYService.removeNotificationQuietHours = function (param) {
            var defer = $q.defer();
            RongCloudLibPlugin.removeNotificationQuietHours(function (ret, err) {
                if (ret) {
                    defer.resolve(ret.status);
                }
            })
            return defer.promise;
        };

        // 获取免打扰设置
        RongYService.getNotificationQuietHours = function (param) {
            var defer = $q.defer();
            RongCloudLibPlugin.getNotificationQuietHours(function (ret, err) {
                if (ret) {
                    defer.resolve(ret.result);
                }
            })
            return defer.promise;
        };
        // 获取最后一次消息
        RongYService.getLatestMessages = function (param) {
            var defer = $q.defer();
            RongCloudLibPlugin.getLatestMessages(param,
                function (ret, err) {
                    if (ret) {
                        defer.resolve(ret.result)
                    }
                    if (err) {
                        console.log("getLatestMessages error: " + JSON.stringify(err));
                    }
                }
            );
            return defer.promise;
        };
        // 获取消息历史记录
        RongYService.getHistoryMessages = function (param) {
            var defer = $q.defer();
            RongCloudLibPlugin.getHistoryMessages(param,
                function (ret, err) {
                    if (ret) {
                        defer.resolve(ret.result)
                    }
                    if (err) {
                        Util.Toast("获取消息记录失败")
                        console.log("getHistoryMessages error: " + JSON.stringify(err));
                    }
                }
            );
            return defer.promise;
        };
        // 发送消息
        RongYService.sendTextMessage = function (param) {
            var defer = $q.defer();
            RongCloudLibPlugin.sendTextMessage(param,
                function (ret, err) {
                    if (ret) {
                        if (ret.status == "prepare") {
                            //消息此时未发送成功，可以根据sentStatus标注样式
                        }
                        // 后续加入发送成功后修改显示样式
                        if (ret.status == "success") {
                            setmsgStatusBroadcast(ret.result.message.messageId, ret.status);
                        }
                        defer.resolve(ret)
                    }
                    if (err) {
                        if (err.code == 21406 || err.code == 22406 || err.code == 23406) {
                            var options = {};
                            options.conversationType = param.conversationType
                            options.targetId = param.targetId
                            RongYService.removeConversation(options).then(function (data) {
                                Util.Toast("该用户不在聊天室中")
                                $location.path("chat/index").replace()
                            })
                        } else {
                            Util.Toast("信息发送失败")
                            setmsgStatusBroadcast(ret.result.message.messageId, ret.status);
                        }
                        console.log("sendTextMessage error: " + JSON.stringify(err));
                    }
                }
            );
            return defer.promise;
        };
        // 发送图片消息
        RongYService.sendImageMessage = function (param) {
            var defer = $q.defer();
            RongCloudLibPlugin.sendImageMessage(param,
                function (ret, err) {
                    if (ret) {
                        // 后续加入发送成功后修改显示样式
                        if (ret.status == "success") {
                            setmsgStatusBroadcast(ret.result.message.messageId, ret.status);
                        }
                        defer.resolve(ret)
                    }
                    if (err) {
                        if (err.code == 21406 || err.code == 22406 || err.code == 23406) {
                            var options = {};
                            options.conversationType = param.conversationType
                            options.targetId = param.targetId
                            RongYService.removeConversation(options).then(function (data) {
                                Util.Toast("该用户不在聊天室中")
                                $location.path("chat/index").replace()
                            })
                        } else {
                            Util.Toast("信息发送失败")
                            setmsgStatusBroadcast(ret.result.message.messageId, ret.status);
                        }
                        console.log("sendImageMessage error: " + JSON.stringify(err));
                    }
                }
            );
            return defer.promise;
        };
        RongYService.sendVoiceMessage = function (param) {
            var defer = $q.defer();
            RongCloudLibPlugin.sendVoiceMessage(param,
                function (ret, err) {
                    if (ret) {
                        if (ret.status == "success") {
                            setmsgStatusBroadcast(ret.result.message.messageId, ret.status);
                        }
                        defer.resolve(ret)
                    }
                    if (err) {
                        if (err.code == 21406 || err.code == 22406 || err.code == 23406) {
                            var options = {};
                            options.conversationType = param.conversationType
                            options.targetId = param.targetId
                            RongYService.removeConversation(options).then(function (data) {
                                Util.Toast("该用户不在聊天室中")
                                $location.path("chat/index").replace()
                            })
                        } else {
                            Util.Toast("信息发送失败")
                            setmsgStatusBroadcast(ret.result.message.messageId, ret.status);
                        }
                        console.log("sendImageMessage error: " + JSON.stringify(err));
                    }
                }
            );
            return defer.promise;
        };
        // 发起聊天
        RongYService.startChat = function (param) {
            var defer = $q.defer();
            var status = ChatStatus.getStatus(); //update or create
            var type = ChatStatus.getChatType(); //讨论组or个人or群组
            var targetId = ChatStatus.getTargetId(); //当前id只有更新时候才传入
            var users = $rootScope.userArr;
            var userIdList = users.map(function (item, index) {
                return item.id
            });
            if (type == ChatStatus.PRIVATE) {
                // 创建群组与单聊同样使用PRIVATE,如果只有一个人则去单聊
                if (status == ChatStatus.CREATE) {
                    if (userIdList.length > 1) {
                        ChatStatus.setChatType(ChatStatus.GROUP);
                        createGroup(userIdList)
                    } else {
                        createPrivate(userIdList[0])
                    }
                } else if (status == ChatStatus.UPDATE) {
                    updateGroup(userIdList, targetId)
                }
            }
            return defer.promise;
        };

        var setmsgStatusBroadcast = function (messageId, status) {
            var statusObj = {}
            statusObj.messageId = messageId;
            statusObj.status = status;
            newMessageEventService.statusBroadcast(statusObj);

        };

        function createPrivate(targetId) {
            _clearUsers();
            RongYService.goPravite(targetId)
        }

        function createGroup(userIdList) {
            var param = {}
            param.userIdList = userIdList
            var groupNames = $rootScope.userArr.map(function (item, index) {
                return item.name
            }).toString()
            //获取群组名字
            param.userIds = userIdList.toString();
            param.groupName = nameFmt(groupNames)
            RongYService.creategroup(param).then(function (data) {
                _clearUsers();
                Groups.push(data)
                RongYService.goGroup(data.pkId)
            })
        }
        function nameFmt(name) {
            if (name && name.length > 7) {
                name = name.slice(0, 7) + "..."
            }
            return name
        }
        function updateGroup(userIdList, targetId) {
            var param = {};
            param.groupId = targetId
            param.userIds = userIdList.toString()
            RongYService.updateGroup(param).then(function (data) {
                _clearUsers();
                RongYService.goGroup(targetId)
            })
        }
        function _clearUsers() {
            $rootScope.userArr = [];
        }
        return RongYService
    })
    .service("newMessageEventService", function ($rootScope) {
        var msgService = {
            broadcast: function (data) { $rootScope.$broadcast("newMsg", data) },
            listen: function (callback) { $rootScope.$on("newMsg", callback) },
            statusBroadcast: function (statusObj) { $rootScope.$broadcast("newMsgStatus", statusObj) },
            statusListen: function (callback) { $rootScope.$on("newMsgStatus", callback) }
        };
        return msgService;
    })
